from . import auth
from .forms import LoginForm
from flask import render_template, redirect, request, url_for, flash
from flask_login import login_user, logout_user, login_required, \
    current_user
from ..models import Student, Professor, Registrar
from .. import db


@auth.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        string_id = str(form.id.data)
        if string_id.startswith("2"):
            user = Student.query.filter_by(student_id=form.id.data).first()
            if user is not None and user.verify_password(form.password.data):
                login_user(user, form.remember_me.data)
                next = request.args.get('next')
                if next is None or not next.startswith('/'):
                    next = url_for('std.student_home')
                return redirect(next)
            flash('用户名或密码错误！')

        elif string_id.startswith("5"):
            user = Professor.query.filter_by(professor_id=form.id.data).first()
            if user is not None and user.verify_password(form.password.data):
                login_user(user, form.remember_me.data)
                next = request.args.get('next')
                if next is None or not next.startswith('/'):
                    next = url_for('pfs.professor_home')
                return redirect(next)
            flash('用户名或密码错误！')

        elif string_id.startswith("1"):
            user = Registrar.query.filter_by(registrar_id=form.id.data).first()
            if user is not None and user.verify_password(form.password.data):
                login_user(user, form.remember_me.data)
                next = request.args.get('next')
                if next is None or not next.startswith('/'):
                    next = url_for('rgs.registrar_home')
                return redirect(next)
            flash('用户名或密码错误！')
        else:
            flash('您输入的用户名错误，请重新输入！')
    return render_template('auth/login.html', form=form)


@auth.route('/logout')
@login_required
def logout():
    logout_user()
    flash('您已退出登录')
    return redirect(url_for('main.index'))
